/**
 * 报销单详情中的【账本导入】【导入结算数据】按钮
 */
import React from 'react';
import moment from 'moment'
import { connect } from 'react-redux'
import { messages, deepFullCopy } from "share/common";
import { Button, message, Alert, Row, Col, Modal } from "antd"

import expenseReportService from 'containers/expense-report/expense-report.service'
import errorMessage from "share/errorMessage";
import chooserData from 'share/chooserData'
import ListSelector from 'components/list-selector'
import Condition from 'components/condition'
import Ellipsis from "ant-design-pro/lib/Ellipsis";
const { If } = Condition;

class ButtonBatchApportion extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      listSelectorVisible: false,
      confirmLoading: false,
      selectAllLoading: false,
      emptyText: '',
      importFrom: '',
      selectedExpenseOIDs: [], //选中的待导入的费用OID
      searchParams: {}, //搜索条件
      messageInfo: '',
    }
  }

  //获取可导入账本的数量
  getAccountExpenseNum = (tag = '') => {
    let emptyText = messages('expense-parent-report.key170')/*这里空空如也*/;
    expenseReportService.getAccountExpenseNum(tag).then(res => {
      if (res.data.success) {
        res.data.total && (emptyText = messages('expense-parent-report.key171')/*无此报销单可见的费用*/);
        this.setState({ listSelectorVisible: true, importFrom: tag || void 0, emptyText });
      }
    });
  };

  //获取账本导入不可见费用
  getInvisibleExpense = ( tag='' ) => {
    let emptyText = messages('expense-parent-report.key170')/*这里空空如也*/;
    let { importFrom, messageInfo } = this.state;
    const { info } = this.props;
    let params = {
      expenseReportOID: info.expenseReportOID,
      importFrom
    };
    expenseReportService.getImportUnavialable (params)
    .then(res => {
      if (res.data.total > 0) {
        let expenseType = [];
        res.data.rows.map((item) => {
          expenseType.push(item.name);
        });
        let expenseTypeString = Array.from(new Set(expenseType)).join('、');
        messageInfo = `${messages('expense-parent-report.key262')/*已隐藏此报销单不可导入的费用*/}：${expenseTypeString}`;
      }
      this.setState({ listSelectorVisible: true, importFrom: tag || void 0, messageInfo, emptyText });
    })
  };

  renderBeforeTable = () => {
    const { messageInfo } = this.state;
    let showMore = () => (
      Modal.info({
        title: messages('components.key1047')/*隐藏费用类型*/,
        content: messageInfo
      })
    );
    return (
      <If value={messageInfo}>
        <Alert
          type="info"
          message={(
            <Row>
              <Col span={22}><Ellipsis lines={1}>{messageInfo}</Ellipsis></Col>
              <Col span={2} style={{textAlign: 'right'}}><a onClick={showMore}>{messages('common.more')/*更多*/}</a></Col>
            </Row>
          )}
          showIcon
          style={{marginBottom: 10}}
        />
      </If>
    )
  };

  //处理导入账本时的selectorItem
  getExpenseSelectorItem = () => {
    const { info } = this.props;
    let selectorItem = chooserData['expense_report_invoice'];
    let searcherData = {
      title: messages('expense-parent-report.key244')/*费用标签*/,
      url: '/api/invoice/factor/filter/invoices',
      key: 'id',
      listKey: 'invoiceLabelDTOS',
    };
    let listExtraParams = {
      expenseReportOID: info.expenseReportOID,
      applicationOID: info.applicationOID,
      userOID: info.applicantOID,
      isOfficialCard : info.isOfficialCard
    };
    selectorItem.searchForm.map(item => {
      if (item.id === 'labelIds') { //费用标签
        item.searcherItem = deepFullCopy(searcherData);
        item.listExtraParams = listExtraParams;
      }
      if (item.id === 'expenseTypeIds') { //费用类型
        searcherData.title = messages('common.expense.type')/*费用类型*/;
        searcherData.key = 'expenseTypeId';
        searcherData.listKey = 'expenseCategorys';
        searcherData.service = data => {
          let expenseTypeDTOS = [];
          data.map(dataItem => {
            dataItem.expenseTypeDTOS.map(subItem => subItem.expenseCategoryName = dataItem.expenseCategoryName);
            expenseTypeDTOS.push(...dataItem.expenseTypeDTOS);
          });
          return expenseTypeDTOS;
        };
        item.searcherItem = searcherData;
        item.listExtraParams = listExtraParams;
      }
    });
    if(["BX001","BX002","BX003","BX004"].includes(info.formCode)){//报销单账本导入查询框隐藏归属人
      let searchForm = selectorItem.searchForm.filter(item => item.id !=  "invoiceOwner")
      selectorItem.searchForm = searchForm
    }
    return selectorItem;
  };

  //导入费用弹框时搜索条件处理
  searchInvoiceEventHandle = (event, value) => {
    if (event === 'DATE_PICKER') { //发生日期
      this.searchRef.formRef.setValues({
        dateOption: undefined
      });
    }
    if (event === 'DATE_RANGE') { //日期范围
      let startDate, endDate;
      endDate = new Date;
      switch (value) {
        case 0: //全部
          startDate = endDate = null;
          break;
        case 1: //近一个月
          startDate = new Date().calcMonth(-1);
          break;
        case 2: //近两个月
          startDate = new Date().calcMonth(-2);
          break;
      }
      this.searchRef.formRef.setValues({
        startEndDate: startDate ? [moment(startDate), moment(endDate)] : null
      });
    }
  };

  //处理导入费用弹框的搜索条件参数
  filterInvoiceSearchParams = (params = {}) => {
    if (params.startEndDate && params.startEndDate[0]) {
      params.startDate = `${moment(moment(params.startEndDate[0]).format('YYYY-MM-DD 00:00:00')).utc().format('YYYY-MM-DDTHH:mm:ss')}Z`;
      params.endDate = `${moment(params.startEndDate[1]).utc().format('YYYY-MM-DDTHH:mm:ss')}Z`;
    } else {
      params.startDate = params.endDate = undefined;
      delete(params.startEndDate);
    }
    delete(params.dateOption);
    this.setState({ searchParams: params });
    return params;
  };

  //选择全部
  handleSelectAllExpense = () => {
    const { info } = this.props;
    const { importFrom, searchParams } = this.state;
    let params = {
      page: 0,
      size: 100, //最多导入100条，若费用超过100条则给提示
      importFrom,
      expenseReportOID: info.expenseReportOID,
      startDate: searchParams.startDate,
      endDate: searchParams.endDate,
      expenseTypeIds: searchParams.expenseTypeIds,
      invoiceOwner: searchParams.invoiceOwner,
      labelIds: searchParams.labelIds,
      isOfficialCard: info.isOfficialCard
    };
    this.setState({ selectAllLoading: true });
    expenseReportService.getAllExpenseByExpenseReport(params).then(res => {
      let invoiceOIDs = [];
      if (res.data && res.data.rows && res.data.rows.invoiceOIDs) {
        if (res.data.rows.invoiceOIDs.length > 100) {
          message.warning(messages('common.max.selected.data', { max: 100 }));
        }
        res.data.rows.invoiceOIDs.map(oid => {
          invoiceOIDs.push({ invoiceOID: oid })
        })
      }
      this.setState({ selectAllLoading: false, selectedExpenseOIDs: invoiceOIDs })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ selectAllLoading: false })
    })
  };

  //账本导入
  handleSelectExpense = (data) => {
    const { info, expenseReportInvoices } = this.props;
    const { importFrom } = this.state;
    if (data && data.result && data.result.length > 0) {
      let invoiceOIDs = [];
      data.result.map(invoice => {
        invoiceOIDs.push(invoice.invoiceOID)
      });
      if (invoiceOIDs.length + expenseReportInvoices.length > 200) {
        message.error(messages('expense-parent-report.key15'/*同一报销单内最多存在200个费用*/));
        return;
      }
      this.setState({ confirmLoading: true });
      expenseReportService.importExpense(info.expenseReportOID, invoiceOIDs, importFrom).then(res => {
        let tip = messages('expense-parent-report.key16'/*账本导入成功*/);
        // if (res && res.data && res.data.message) {
        //   tip = res.data.message;
        // }
        message.success(tip);  //费用导入成功
        this.setState({ confirmLoading: false, selectedExpenseOIDs: [], listSelectorVisible: false });
        this.props.onSuccess();
      }).catch(err => {
        this.setState({ confirmLoading:false });
        message.error(err.response.data.message);
      });
    } else {
      this.setState({ listSelectorVisible: false })
    }
  };

  render() {
    const { info, form } = this.props;
    let extraParams = this.props.extraParams || {};
    extraParams.isOfficialCard= info.isOfficialCard;
    const { listSelectorVisible, confirmLoading, selectAllLoading, emptyText, importFrom, selectedExpenseOIDs } = this.state;
    return (
      <div style={{display: 'inline-block'}}>
        <Button type="primary" onClick={() => this.getInvisibleExpense()}>
          {messages('expense-parent-report.key35'/*账本导入*/)}
        </Button>
        <If value={form.customFormPropertyMap && form.customFormPropertyMap['import.unify.data'] === 'true'}>
          <Button onClick={() => this.getAccountExpenseNum('publicBook')}>
            {messages('expense-parent-report.key215')/*导入结算数据*/}
          </Button>
        </If>
        <ListSelector
          type="expense_report_invoice"
          method="post"
          visible={listSelectorVisible}
          locale={{ emptyText }}
          beforeTable={this.renderBeforeTable()}
          selectorItem={this.getExpenseSelectorItem()}
          extraParams={{ expenseReportOID: info.expenseReportOID, importFrom, ...extraParams }}
          maxNum={100}
          selectAll
          selectAllHolding
          confirmLoading={confirmLoading}
          selectAllLoading={selectAllLoading}
          selectedData={selectedExpenseOIDs}
          wrappedComponentRef={inst => this.searchRef = inst}
          eventHandle={this.searchInvoiceEventHandle}
          filterSearchParams={this.filterInvoiceSearchParams}
          onSelectAll={this.handleSelectAllExpense}
          onOk={this.handleSelectExpense}
          onCancel={() => this.setState({listSelectorVisible: false, selectedExpenseOIDs: []})}
        />
      </div>
    )
  }
}

ButtonBatchApportion.propTypes = {
  info: React.PropTypes.object,
  form: React.PropTypes.object,
  expenseReportInvoices: React.PropTypes.array,
  onSuccess: React.PropTypes.func,
  extraParams: React.PropTypes.object // 弹窗搜索的额外自定义搜索参数，搜索字段不存在于弹窗内部的筛选组件
};

ButtonBatchApportion.defaultProps = {
  extraParams: {}
}

function mapStateToProps(state) {
  return { }
}

export default connect(mapStateToProps)(ButtonBatchApportion)
